export default class WS {
	constructor(config){
		this.ws = config.url
		this.timer = null
		this.timeOut = null
		this.rtimer = null
		this.wsState = 0
	}
	
	//重置
	reset(){
		this.timer && clearInterval(this.timer)
		this.timer = null
		this.timeOut && clearInterval(this.timeOut)
		this.timeOut = null
		this.rtimer = null
		this.rtimer && clearInterval(this.rtimer)
		this.wsState = 0
	}
	//连接
	connect(){
		if(this.wsState == 1){
			return
		}
		if(this.ws){
			let that = this
			uni.connectSocket({
				url:that.ws,
				header: {
				  'content-type': 'application/json'
				  },
				  success(res) {
				  	uni.onSocketOpen(that.onWsConnect.bind(that))
				  	uni.onSocketError(that.onWsError.bind(that)) 
				  	uni.onSocketMessage(that.onWsMessage.bind(that)) 
				  	uni.onSocketClose(that.onWsColse.bind(that)) 
				  },
				  fail(err) {
				  	console.log('err',err);
				  }
			})
		}
	}
	
	//发送消息
	sendMesssage(msg){
		uni.sendSocketMessage({
			data:msg
		})
	}
	
	//关闭连接
	close(){
		uni.closeSocket()
	}
	//连接成功
	onWsConnect(){
		console.log('WebSocket连接已连接成功！');
		this.wsState = 1
		if(this.rtimer){
			clearInterval(this.rtimer)
			this.rtimer = null
		}
		if(this.timer){
			clearInterval(this.timer)
			this.timer = null
		}
		this.heartCheck()
	}
	
	//心跳检测
	heartCheck(){
		const userId = uni.getStorageSync('userId')
		if(userId){
			let msg = {
			  message: "ping",
			  userId: userId
			}
			this.timer = setInterval(()=>{
				this.sendMesssage(JSON.stringify(msg))
				if(!this.timeOut){
					this.timeOut = setTimeout(()=>{
						clearInterval(this.timer)
						console.log('心跳检测失败，准备重连');
						const userId = uni.getStorageSync('userId')
						if(userId){
							this.close()							
							this.reset()
						}
					},15*1000)
				}
			},1000*5)
		}
	}
	
	//连接关闭
	onWsColse(res){
		console.log('WebSocket连接已关闭！',res);
		const userId = uni.getStorageSync('userId')
		if(userId){
			this.reset()
		}
	}
	
	//接受消息
	onWsMessage(res){
		const { data} =res
		console.log('接受ws的msg',data);
		let msg = JSON.parse(data)
		clearTimeout(this.timeOut)
		this.timeOut = null
		if(!msg){
			return
		}
		if(msg.type == 1){
			const content = '离线:'+msg.message
			uni.createPushMessage({
				content,
				payload:{
					type:msg.type
				}
			})
		}
		if(msg.type == 2){
			const content = '告警:'+msg.message
			uni.createPushMessage({
				content,
				payload:{
					type:msg.type
				}
			})
		}
		
	}
	
	//连接错误
	onWsError(err){
		console.log('WebSocket连接错误！',err);
		const userId = uni.getStorageSync('userId')
		if(userId){
			this.close()
			this.reset()
		}
	}
}